package com.example.publice.validate;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.example.publice.error.DataValidateException;

/**
 * 数据验证
 * 
 * @author wangkai
 *
 * @param <T>
 * @date: 2019年6月20日 下午2:46:18
 */
public abstract class DataValidator<T> {

	public abstract void validate() throws Exception;

	protected T data;

	public DataValidator(T data) {
		this.data = data;
	}

	/**
	 * 空值验证
	 * 
	 * @param ex
	 * @param msg
	 * @throws DataValidateException
	 */
	protected void notEmpty(Expression<?, T> ex, String msg) throws DataValidateException {
		Object obj = ex.select(this.data);
		if (obj instanceof String) {
			String str = (String) obj;
			if (!StringUtils.isNotEmpty(str)) {
				throw new DataValidateException(msg);
			}
		} else {
			if (obj == null) {
				throw new DataValidateException(msg);
			}
		}
	}

	/**
	 * 最大长度验证
	 * 
	 * @param ex
	 * @param max
	 * @param msg
	 * @throws DataValidateException
	 */
	protected void maxLan(Expression<?, T> ex, int max, String msg) throws DataValidateException {
		Object obj = ex.select(this.data);
		if (!(obj != null && obj.toString().trim().length() <= max)) {
			throw new DataValidateException(msg);
		}
	}

	/**
	 * 最小长度验证
	 * 
	 * @param ex
	 * @param min
	 * @param msg
	 * @throws DataValidateException
	 */
	protected void minLan(Expression<?, T> ex, int min, String msg) throws DataValidateException {
		Object obj = ex.select(this.data);
		if (!(obj != null && obj.toString().trim().length() >= min)) {
			throw new DataValidateException(msg);
		}
	}

	/**
	 * 手机号验证
	 * 
	 * @param ex
	 * @param msg
	 * @throws DataValidateException
	 */
	protected void isTelephone(Expression<String, T> ex, String msg) throws DataValidateException {
		String phone = ex.select(this.data);
		if (!StringUtils.isNotEmpty(phone) || phone.trim().length() != 11
				|| !Pattern.matches("^1(?:3|4|5|6|7|8)\\d{9}$", phone)) {
			throw new DataValidateException(msg);
		}
	}


	public void setData(T data) {
		this.data = data;
	}

}
